<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <!-- import CSS -->
  <title>位置监控</title>
  <link rel="shortcut icon" href="../favicon.ico">
  <link rel="stylesheet" href="../plugins/ElementUI/index-2.3.9.css">
  <link href="../css/common.css" rel="stylesheet">
  <style type="text/css">
    .el-aside {
      /* background-color: #D3DCE6; */
      color: #333;
      padding: 20px 0px 20px 5px;
    }
    .el-main {
      /* background-color: #E9EEF3; */
      color: #333;
      text-align: center;
    }
    .el-dialog{width: 80%}
    .el-container {
      height: 100%;
    }
    /* baidu map */
    body, html,#allmap {width: 100%;height: 100%;overflow: hidden;margin:0;font-family:"微软雅黑";}
		#l-map{height:100%;width:78%;float:left;border-right:2px solid #bcbcbc;}
		#r-result{height:100%;width:20%;float:left;}
  </style>
  <!-- map -->
  <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=ePOIA9rln4os58j2HQnx3AW0Sdy9MiQv"></script>
  <!-- import Vue before Element -->
  <script src="../plugins/ElementUI/vue-2.5.16.js" type="text/javascript"></script>
  <!-- import JavaScript -->
  <script src="../plugins/ElementUI/index-2.3.9.js" type="text/javascript"></script>
  <script src="../plugins/ElementUI/vue-resource.min.js"></script>
  <script src="../plugins/ECharts/echarts-4.1.0.js"></script>
</head>
<body>
  <div id="appp" class="animated fadeInRight" v-cloak>
    <el-container>
      <el-aside width="250px">        
        <el-tree
          :props="defaultProps"
          :load="loadNode"
          node-key="id"
          :default-expanded-keys="[0]"
          lazy
          ref="tree"
          show-checkbox
          @check-change="handleCheckChange"
          @check="handleCheck">
        </el-tree>
      </el-tree>
      </el-aside>
      <el-main>
        <div id="allmap"></div>
      </el-main>
    </el-container>
    <!-- dialog Information -->
    <dialog-status 
      :dialogmiss="dialogInfo"
      :vincodemini="vinCodemini"
      @dialog-hidden="dialogHid">
    </dialog-status>
  </div>
</body>
  <script src="../plugins/Underscore/underscore-min.js"></script>
  <script src="../js/ApiRequest.js"></script>
  <script src="../js/mars2baidu.js"></script>
  <script src="../js/vehicleInfo.js"></script>
  <script>
    var map,point,opts;
    var vm = new Vue({
      el: '#appp',
      components:{
          'dialog-status': ComponentA
      },
      data: function() {
        return { 
          windowHeight: (window.innerHeight||(document.documentElement&&document.documentElement.clientHeight)||document.body.clientHeight) - 270,
          locationInfo:[],
          vinCodemini:'',
          currentPagemini :1,
          dialogInfo: false,
          // 以下新增
          defaultProps:{
            children: 'childDepartment',
            label: 'departmentName',
            isLeaf:'lastLeaf',
            type:'departmentType'
          },
          carImg:"../img/car.png",
          checkStatus:null,
          vehicleLocalInfo:{}
        }
      },
      mounted:function(){
        this.$nextTick(function(){
          this.showDefaultMap()
        })
      },
      methods: {
          dialogHid:function(){
            this.dialogInfo = false
          },   
          // 车辆详情 -- 仪表盘
          carInfoClick:function(index,row){
            if(!row.locationInfo){
              this.$message({message:"sorry,未找到定位数据！！"})
              return
            }
            this.vinCodemini = row.vinCode;
            this.dialogInfo = true;
          },
          showDefaultMap:function(){
            map = new BMap.Map("allmap",{enableMapClick:false});    // 创建Map实例
            map.centerAndZoom(new BMap.Point(108.897597,34.457814),6);  // 初始化地图,设置中心点坐标和地图级别	  
            map.addControl(new BMap.MapTypeControl({
              mapTypes:[ BMAP_NORMAL_MAP,  BMAP_HYBRID_MAP]
            }));
            map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放
          },
          showMap:function(points){//显示 Baidu 地图
            // 百度地图API功能
            map = new BMap.Map("allmap",{enableMapClick:false});
            map.enableScrollWheelZoom();   //启用滚轮放大缩小，默认禁用
	          map.enableContinuousZoom();    //启用地图惯性拖拽，默认禁用
            // map.setMapStyle({style:'grayscale'});
            var size = new BMap.Size(10, 20);
            map.addControl(new BMap.CityListControl({
              anchor: BMAP_ANCHOR_TOP_LEFT,
              offset: size
            }));
            point = new BMap.Point(points[0].lng, points[0].lat);
            map.centerAndZoom(point, 15);
            // 编写自定义函数,创建标注
            function addMarker(pointt,item){
              var myIcon = new BMap.Icon("http://lbsyun.baidu.com/jsdemo/img/car.png", new BMap.Size(52,26), {    
                  // 指定定位位置。   
                  // 当标注显示在地图上时，其所指向的地理位置距离图标左上    
                  // 角各偏移10像素和25像素。您可以看到在本例中该位置即是   
                  // 图标中央下端的尖角位置。    
                  anchor: new BMap.Size(26, 13),    
                  // 设置图片偏移。   
                  // 当您需要从一幅较大的图片中截取某部分作为标注图标时，您   
                  // 需要指定大图的偏移位置，此做法与css sprites技术类似。    
                  // imageOffset: new BMap.Size(0, 0)   // 设置图片偏移    
              }); 
              // 创建标注对象并添加到地图   
              var marker = new BMap.Marker(pointt, {icon: myIcon});    
              map.addOverlay(marker);              
              opts = {
                width : 200,     // 信息窗口宽度
                height: 100,     // 信息窗口高度
                title : "盾泰云平台" , // 信息窗口标题
                enableMessage:true,//设置允许信息窗发送短息
                message:"盾泰云，守护每一辆车~"
              }
              var infoWindow = new BMap.InfoWindow("vin:"+item.vin, opts);  // 创建信息窗口对象 
              marker.addEventListener("click", function(){          
                map.openInfoWindow(infoWindow,pointt); //开启信息窗口
              });
            }
            // 向地图添加标注
            for (var i = 0; i < points.length; i ++) {
              var pointt = new BMap.Point(points[i].lng,points[i].lat);
              // console.log(i,this.locationInfo[i])
              addMarker(pointt,this.locationInfo[i]);
            }
          },
          // 首次加载组织
          responseSyncTree(id,callback){
            resourceRequst("/department/queryAllVehicleListInDepartment",{departmentId:id},function(res){
              if(typeof callback == "function") callback(res)
            },true)
          },
          loadNode(node, resolve) {
            var _this = this;
            if (node.level === 0) {
              var treeData = [{ 
                    departmentName: '上海同捷',
                    departmentType:1,
                    id: 0,
                    childDepartment:[]
                }]
              return resolve(treeData);
            }
            if(node.level !== 0){              
              setTimeout(() => {
                this.responseSyncTree(node.data.id,function(res){
                  var dataTree = [];
                  var department = res.departmentList;
                  var vehicle = res.vehicleList;
                  if(department && Object.keys(department).length){
                    _.each(department,function(value){
                      value.lastLeaf = false 
                      dataTree.push(value)
                    })
                  }
                  if(vehicle && Object.keys(vehicle).length){
                    _.each(vehicle,function(value){
                      value.departmentName = value.plateNo
                      value.departmentType = -1
                      value.lastLeaf = true 
                      dataTree.push(value)
                    })
                  }
                  return  resolve(dataTree)
                })
              }, 500);
            }
          },
          /** 
           * CheckBox选中请求车辆详细信息
           * departmentType === -1 车辆
           * departmentType !== -1 组织
           * ------------------------------------------
           * showLocalIcon 根据车辆位置在地图显示
           * removeLocalIcon 根据车辆Code隐藏已显示的车辆
           * */ 
          handleCheck(data,data2){
            // console.log(this.$refs.tree.getCheckedNodes(true))
            var _this = this;
            if(data.departmentType === -1){
              resourceRequst("/location/queryLatestVehicleLocationByVin",{vin:data.vinCode},function(res){
                var loction = res.vehicleInfo.locationInfo;
                if(loction){
                  if(parseFloat(loction.lat) == 0 || parseFloat(loction.lng) == 0) {
                    _this.$message({
                      message: '警告：'+res.vehicleInfo.plateNo+' 车辆位置异常！',
                      type: 'warning'
                    });
                  }else{
                    _this.handleResponseData(res.vehicleInfo)
                  }
                }else{
                  _this.$message({
                    message: '警告：车辆暂无定位信息！',
                    type: 'error'
                  });
                }
                return
              },true)
            }else{
              resourceRequst("/location/queryAllVehicleLocationByDepartment",{departmentId:data.id},function(res){
                if(res.list.length){
                  _this.handleResponseData(res.list,true)
                }else{
                  _this.$message({
                    message: '消息：暂无定位信息！',
                  });
                }
              },true)
            }
          },
          handleCheckChange(data,status){
            this.checkStatus = status//赋值当前CheckBox是否是选中状态；
          },
          handleResponseData(data,flag){
            var vehicleArr = this.vehicleLocalInfo;
            var isCheck = this.checkStatus;//是否是选中状态
            var vehicleList = {
              localtion:{},
              carInfo:{}
            }
            /* flag 是否是组织 */            
            if(flag){
                if(isCheck){//若是选中状态-----则需要过滤已经存在的车辆
                  data.forEach(element => {
                    var isExist = vehicleArr.hasOwnProperty(element.vinCode);//判断已显示的车辆是否包含当前车辆-----如果包含则跳过--否则add进去   
                    if(isExist){
                      // console.log("已存在--跳过")
                    }else{              
                      vehicleList.carInfo = element;
                      vehicleList.localtion = element.locationInfo;
                      vehicleArr[element.vinCode] = vehicleList   

                      this.showLocalIcon(vehicleList)
                    }
                  });
                }else{//若不是选中状态-----则清除组织内的所有车辆
                  data.forEach(element => {
                    var isExist = vehicleArr.hasOwnProperty(element.vinCode);//判断已显示的车辆是否包含当前车辆-----如果包含清除
                    if(isExist){
                      // 删除
                      delete vehicleArr[element.vinCode]
                      this.removeLocalIcon(element.vinCode)
                    }
                  });
                }
            }
            else{//非组织
              var isExist = vehicleArr.hasOwnProperty(data.vinCode);//判断已显示的车辆是否包含当前车辆-----如果包含则跳过--否则add进去            
              if(isExist){
                // 删除
                delete vehicleArr[data.vinCode]
                this.removeLocalIcon(data.vinCode)
              }else{              
                vehicleList.carInfo = data;
                vehicleList.localtion = data.locationInfo;
                vehicleArr[data.vinCode] = vehicleList ;

                this.showLocalIcon(vehicleList)
              }
            }             
          },
          showLocalIcon(data){
            if(!data.localtion){
              this.$notify({
                title: '警告',
                message: `警告：${data.carInfo.plateNo} 车辆位置异常！`,
                type: 'warning'
              });
              return
            } 
            var point = coordtransform.wgs84togbd09(data.localtion.lng, data.localtion.lat);
            var pointBD = new BMap.Point(point[0], point[1]);
            
            // 编写自定义函数,创建标注
            var geoc = new BMap.Geocoder();
            var myIcon = new BMap.Icon(this.carImg, new BMap.Size(26, 26));
            var marker = new BMap.Marker(pointBD, { icon: myIcon });
            marker.vinCode = data.carInfo.vinCode;
            map.addOverlay(marker);
            // 气泡 // 添加窗口信息
            var opts = {
                // width: 250,
            };
            var infoWindow = null;
            geoc.getLocation(pointBD, function (rs) {
                var addComp = rs.addressComponents;
                var address = `${addComp.province}${addComp.city}${addComp.district}${addComp.street}${addComp.streetNumber}`;        
                // <div>车牌号：${data.carInfo.plateNo ? data.carInfo.plateNo : '未知'}</div>
                // <div>时间：${data.carInfo.plateNo ? info.locationEntity.rptutc : '未知'}</div>
                // <div>速度：${info.locationEntity.spd ? parseFloat(info.locationEntity.spd).toFixed(2) +"（km/h）" : '未知'}</div>
                // <div>状态：${info.vehicleEntity.online ? "在线" : '离线'}</div>
                // <div>卫星数：${info.locationEntity ? info.locationEntity.sat : '未知'}</div>
                // <div>定位精度：${info.locationEntity ? parseFloat(info.locationEntity.hdop).toFixed(2) + "（m）" : '未知'}</div>
                // <div>海拔：${info.locationEntity ? parseFloat(info.locationEntity.att).toFixed(2) + "（m）" : '未知'}</div>
                // <div>当前航向：${info.locationEntity ? parseFloat(info.locationEntity.head).toFixed(2) + "°" : '未知'}</div>
                var innerText = `
                    <div>车牌号：${data.carInfo.plateNo ? data.carInfo.plateNo : '未知'}</div>
                    <div>速度：${data.localtion.speed ? parseFloat(data.localtion.speed).toFixed(2) +"（km/h）" : '未知'}</div>
                    <div>位置：${address ? address : '未知'}</div>
                    <div>定位时间：${data.localtion.uploadTime ? data.localtion.uploadTime : '未知'}</div>
                `;
                
                infoWindow = new BMap.InfoWindow(innerText, opts); // 创建信息窗口对象
                marker.openInfoWindow(infoWindow); //开启信息窗口
            }); 
            
            map.centerAndZoom(pointBD, 11);

            marker.addEventListener("click", function () {
                map.openInfoWindow(infoWindow, pointBD);
            });
          },
          removeLocalIcon(data){
            var allOverlay = map.getOverlays();    
            for (var i = 0; i < allOverlay.length; i++) {
                if (data.includes(allOverlay[i].vinCode)) {
                    map.removeOverlay(allOverlay[i]);
                }
            }
          },
          // 显示车辆点集合
          showPoints(points,flag){
              if (!Object.keys(points).length) { map.clearOverlays();  return}
              // 转换所有坐标点  
              const pointArry = []
              const infoArry = []
              for (const key in points) {
                  if (points.hasOwnProperty(key)) {
                      let location = points[key].locationEntity;
                      if(!location){
                          let plateNo = points[key].vehicleEntity.plateNo
                          notification['warning']({
                              message: '定位异常警告',
                              description: `车牌号：${plateNo} 异常`,
                              duration: 2.5
                          });
                          break;
                      }
                      // var wgs84togcj02 = coordtransform.wgs84togcj02(location.lng, location.lat);
                      // var gcj02tobd09 = coordtransform.gcj02tobd09(wgs84togcj02[0], wgs84togcj02[1]);
                      var pointt = coordtransform.wgs84togbd09(location.lng, location.lat);
                      var pointBD = new BMap.Point(pointt[0], pointt[1]);
                      pointArry.push(pointBD)
                      infoArry.push(points[key])
                  }
              }    
              // 编写自定义函数,创建标注
              var geoc = new BMap.Geocoder();
              var myIcon = new BMap.Icon(this.carImg, new BMap.Size(26, 26));
              function addMarker(point,info) {
                  var marker = new BMap.Marker(point, { icon: myIcon });
                  marker.imei = info.iccid
                  map.addOverlay(marker);
                  // 气泡 // 添加窗口信息
                  var opts = {
                      width: 250,
                  };
                  var infoWindow = null;
                  geoc.getLocation(point, function (rs) {
                      var addComp = rs.addressComponents;
                      var address = `${addComp.province}${addComp.city}${addComp.district}${addComp.street}${addComp.streetNumber}`;        
                      var innerText = `
                          <div>编号：${info.iccid ? info.iccid : '未知'}</div>
                          <div>车牌号：${info.vehicleEntity ? info.vehicleEntity.plateNo : '未知'}</div>
                          <div>时间：${info.locationEntity ? info.locationEntity.rptutc : '未知'}</div>
                          <div>速度：${info.locationEntity.spd ? parseFloat(info.locationEntity.spd).toFixed(2) +"（km/h）" : '未知'}</div>
                          <div>状态：${info.vehicleEntity.online ? "在线" : '离线'}</div>
                          <div>卫星数：${info.locationEntity ? info.locationEntity.sat : '未知'}</div>
                          <div>定位精度：${info.locationEntity ? parseFloat(info.locationEntity.hdop).toFixed(2) + "（m）" : '未知'}</div>
                          <div>海拔：${info.locationEntity ? parseFloat(info.locationEntity.att).toFixed(2) + "（m）" : '未知'}</div>
                          <div>当前航向：${info.locationEntity ? parseFloat(info.locationEntity.head).toFixed(2) + "°" : '未知'}</div>
                          <div>位置：${address ? address : '未知'}</div>
                      `;
                      
                      infoWindow = new BMap.InfoWindow(innerText, opts); // 创建信息窗口对象
                      if (pointArry.length == 1){
                          marker.openInfoWindow(infoWindow); //开启信息窗口
                      }
                  }); 
                  marker.addEventListener("click", function () {
                      map.openInfoWindow(infoWindow, point);
                  });
              }
              for( var i=0; i<pointArry.length; i++){
                  addMarker(pointArry[i], infoArry[i]);
              }
              if (pointArry.length == 1){
                  map.centerAndZoom(pointArry[0], 11);
                  return   
              }
              map.setViewport(pointArry)      
          },
          // 删除指定覆盖物
          removeMapMarker (points){        
              const { map } = this.state
              var allOverlay = map.getOverlays();
              var delList = [];
              for (var i = 0; i < points.length; i++) {
                  delList[i] = points[i].iccid
              }     
              for (var i = 0; i < allOverlay.length; i++) {
                  if (delList.includes(allOverlay[i].imei)) {
                      map.removeOverlay(allOverlay[i]);
                  }
              }
          }
      },
    })
  </script>
</html>